<?php
$this->breadcrumbs=array(
	'Pages'=>array('index'),
	'Manage',
);

$this->menu=array(
    array('label'=>'Create Page', 'url'=>array('create')),
    array('label'=>'Activate selected pages', 'url'=>array('/Core/service/ajax', "SID"=>"Cms.page.changeStatus", 'value'=>1), 'linkOptions'=>array('class'=>'change-status')),
	array('label'=>'Deactivate selected pages', 'url'=>array('/Core/service/ajax', "SID"=>"Cms.page.changeStatus", 'value'=>0), 'linkOptions'=>array('class'=>'change-status')),
    array('label'=>'Copy selected pages', 'url'=>'#', 'linkOptions'=>array('class'=>'copy-pages')),
);
$cs = Yii::app()->clientScript;

$script = "
jQuery('#page-grid .status-column a').live('click',function() {
    jQuery.fn.yiiGridView.update('page-grid', {
        url:jQuery(this).attr('href'),
        success:function() {
            jQuery.fn.yiiGridView.update('page-grid');
        }
    });
    return false;
});
jQuery('.crud-menu .change-status').live('click',function() {
    var data = [];
    jQuery.each(jQuery('input.select-on-check'), function(){
        if (jQuery(this).attr('checked'))
            data.push(jQuery(this).val());
    });
    if (data.length <= 0)
    {
        alert('No item selected.');
        return false;
    }
    
    jQuery.fn.yiiGridView.update('page-grid', {
        url:jQuery(this).attr('href'),
        data : {'ids' : data},
        success:function() {
            jQuery.fn.yiiGridView.update('page-grid');
        }
    });
    return false;
});

jQuery.fn.set_filter_site_id = function(value)
{
    var filter = jQuery('<input type=\"hidden\" name=\"Page[template_content_id]\" />').val();
    jQuery('.filters td:first').append(filter);
}
jQuery.fn.set_filter_site_id({$model->site_id});

jQuery('#site').change(function(){
    jQuery.fn.set_filter_site_id(jQuery('#site').val());
    filter.trigger('change');
});
jQuery('body').ajaxSuccess(function(){
    jQuery.fn.set_filter_site_id(jQuery('#site').val());
});
";
$cs->registerScript(__CLASS__.'#ChangeStatus', $script, CClientScript::POS_READY);

$script = "
function get_link_delete(url, data)
{
    var valid = true;
    var delete_data = 0;
    if (confirm('Do you want to delete the page content also ?\\nContent used by other pages will not be delete. You will be able to confirm your deletion on the next step.'))
    {
        delete_data = 1;
        if (!confirm('Are you sure to delete the page and its content ?'))
            valid = false;
    }
    else
        if (!confirm('Are you sure to delete the page ? Page content will not be deleted.'))
            valid = false;
    
    data = jQuery.extend({'delete_data' : delete_data}, data);
    return {
        url : jQuery.param.querystring(url, data),
        valid : valid
    };
}

jQuery('.actions-column a.delete').live('click', function(){
    var _this = jQuery(this);
    
    var url = jQuery(this).attr('href');
    var data = get_link_delete(url, {});
    if (data.valid == false)
        return false;
    
    jQuery.post(data.url, function(res){
        jQuery('.grid-view').load('".$this->createUrl('/Cms/admin/page/admin')." .grid-view > *', function(){
            jQuery.initNestedSortable();
        });
    });
    return false;
});
jQuery('.delete-multi').live('click', function(){
    var data = [];
    jQuery.each(jQuery('.checkbox-column input:checked'), function(){
        data.push(jQuery(this).val());
    });
    if (data.length <= 0) {
        alert('Please select at least one category');
        return false;
    }
    
    var url = '".$this->createUrl('delete')."';
    data = get_link_delete(url, {'ids' : data});
    if (data.valid == false)
        return false;
    
    jQuery.post(data.url, function(res){
        jQuery('.grid-view').load('".$this->createUrl('/Cms/admin/page/admin')." .grid-view > *', function(){
            jQuery.initNestedSortable();
        });
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#Actions', $script, CClientScript::POS_READY);
?>

<h1>Manage Pages</h1>

<style type="text/css">
.grid-view {padding-top: 2px;}
.grid-view .summary {text-align: left;}
</style>
<div class="view-mode" style="margin-bottom: -20px;"><?php echo CHtml::link('Tree View', array('admin'), array('class'=>'tree', 'title'=>'Tree View'));?></div>
<?php 
$baseScriptUrl = Yii::app()->getAssetManager()->publish(Yii::getPathOfAlias('zii.widgets.assets')).'/gridview';
$grid = $this->widget('zii.widgets.grid.CGridView', array(
	'id'=>'page-grid',
	'dataProvider'=>$model->search(),
	'filter'=>$model,
    'selectableRows'=>2,
    'selectionChanged'=>"updateSelectors",
	'columns'=>array(
        array(
            'class'=>'CCheckBoxColumn',
            'value'=>'$data->id',
            'htmlOptions'=>array('width'=>'3%'),
        ), 
        array(
            'name'=>'title',
            'type'=>'raw',
            'value'=>'CHtml::link($data->title, array("update", "id"=>$data->id), array("title"=>"Updated: ".Yii::app()->getDateFormatter()->formatDateTime(strtotime($data->last_update))." - Created: ".Yii::app()->getDateFormatter()->formatDateTime(strtotime($data->creation_datetime))))',
            'htmlOptions'=>array(
                'class'=>'sort-handle',
            )
        ), 
        array(
            'header'=>'Notes',
            'name'=>'note',
            'type'=>'raw',
            'value'=>'"<div><span>".$data->note."</span> ".CHtml::link(CHtml::image("'.$baseScriptUrl.'/update.png", "Edit Note"), array("editLog", "id"=>$data->id), array("class"=>"edit-log", "title"=>"Edit Note"))."</div>"',
        ),
        array(
            'name' => 'defaultUrl',
            'type' => 'raw',
            'value' => 'is_object($data->defaultUrl) ? $data->defaultUrl->url."<br/>(".$data->alias.")" : ""',
        ),
        array(
            'name' => 'id',
            'header'=>'Live',
            'filter'=>false,
            'sortable'=>false,
            'type' => 'html',
            'value' => 'CHtml::image(Yii::app()->theme->baseUrl."/images/".(FSM::_run("Cms.workflow.isActiveInLive", array("page_id"=>$data->id))->status ? "log_severity1" : "delicon").".gif", "Live")',
            'htmlOptions'=>array(
                'align'=>'center',
            )
        ),
        array(
            'name'=>'include_in_sitemap',
            'header'=>'Sitemap',
            'type'=>'raw',
            'value'=>'CHtml::link($data->include_in_sitemap, array("/Core/service/ajax", "SID"=>"Cms.page.includeInSitemap", "ids[]"=>$data->id, "value"=>$data->include_in_sitemap ? 0 : 1), array("class"=>($data->include_in_sitemap ? "active" : "")))',
            'filter'=>false,
            'sortable'=>false,
            'htmlOptions'=>array(
                'class'=>'status-column',
                'style'=>'width:70px;',
            )
        ),
        array(
            'name'=>'status',
            'type'=>'raw',
            'value'=>'CHtml::link($data->statusText, array("/Core/service/ajax", "SID"=>"Cms.page.changeStatus", "ids[]"=>$data->id, "value"=>$data->status ? 0 : 1), array("class"=>($data->status ? "active" : "")))',
            'filter'=>false,
            'sortable'=>false,
            'htmlOptions'=>array(
                'class'=>'status-column'
            )
        ),
		array(
			'class'=>'CButtonColumn',
			'template'=>'{duplicate} {copy} {goto} {update} {delete-page}',
            'buttons'=>array(
                'duplicate'=>array(
                    'label'=>'Duplicate',
                    'imageUrl'=>Yii::app()->theme->baseUrl.'/images/duplicate-page.png',
                    'url'=>'"#".$data->id',
                    'visible'=>'$data->type!=Page::TYPE_GROUP',
                    'options'=>array(
                        'class'=>'duplicate',
                    ),
                ),
                'copy'=>array(
                    'label'=>'Copy',
                    'imageUrl'=>Yii::app()->theme->baseUrl.'/images/copy-page.png',
                    'url'=>'"#".$data->id',
                    'visible'=>'$data->type!=Page::TYPE_GROUP',
                    'options'=>array(
                        'class'=>'copy',
                    ),
                ),
                'delete-page'=>array(
                    'label'=>'Delete',
                    'imageUrl'=>Yii::app()->theme->baseUrl.'/images/delete.png',
                    'url'=>'Yii::app()->controller->createUrl("delete", array("ids[]"=>$data->id))',
                    'options'=>array(
                        'class'=>'delete',
                    ),
                ),
                'goto'=>array(
                    'label'=>'Go to',
                    'imageUrl'=>Yii::app()->theme->baseUrl.'/images/link-go.png',
                    'url'=>'is_object($data->defaultUrl) && is_object($lastestRevision = $data->lastestRevision) ? Yii::app()->request->hostInfo."/".trim($data->defaultUrl->url, "/")."?revision=".$lastestRevision->id : "#"',
                    'visible'=>'$data->type!=Page::TYPE_GROUP',
                    'options'=>array('target'=>'_blank'),
                )
            ),
            'htmlOptions'=>array(
                'class'=>'actions-column',
                'width'=>100,
            )
		),
	),
)); 

if ($grid->dataProvider->ItemCount) {
    $this->menu[] = array('label' => 'Delete selected pages', 'url'=>$this->createUrl('delete'), 'linkOptions' => array('class'=>'delete-multi'));
}
$cs->registerScriptFile(Yii::app()->core->AssetUrl.'/scripts/gridview.js', CClientScript::POS_BEGIN);
?>
<?php $this->renderPartial('_form_copy', array('sites'=>$sites));?>
<?php $this->renderPartial('_form_duplicate');?>
<?php
$script = "
jQuery.edit_log_link = '';
jQuery('.edit-log').live('click', function(){
    jQuery.edit_log_link = jQuery(this);
    jQuery('#edit-log textarea').val(jQuery(this).prev('span').text());
    jQuery.fancybox({
        'type' : 'inline',
        'href' : '#edit-log',
        'autoScale'     : false,
        'titleShow'     : false,
        'hideOnOverlayClick'     : false,
        'width'         : 398,
        'model'         : true
    });
    return false;
});

jQuery('#edit-log .save-log').live('click', function(){
    jQuery.fancybox.close();
    var data = jQuery('#edit-log textarea').val();
    jQuery.post(jQuery.edit_log_link.attr('href'), {data : data}, function(){
        jQuery.edit_log_link.prev('span').text(data);
    });
    return false;
});
";
$cs->registerScript(__CLASS__.'#EditLog', $script);
?>
<div style="display: none;">
    <div id="edit-log" style="width: 398px;">
        <div><?php echo CHtml::textArea('log', '', array('cols'=>70, 'rows'=>7, 'style'=>'width:388px;'));?></div>
        <div align="right">
            <?php echo CHtml::button('Cancel', array('class'=>'cancel'));?>
            <?php echo CHtml::button('Save', array('class'=>'save-log'));?>
        </div>
    </div>
</div>